package ink.xieyu.utils.scan;

import ink.xieyu.ex.BeanBuilderException;

import java.io.File;
import java.util.*;
import java.util.logging.Logger;

public class ScanAllClass {

    public static <T> void run(Class<T> startClass, String[] args) {
        try {
            new ScanAllClass().start(startClass);
        } catch (BeanBuilderException e) {
            e.printStackTrace();
        }
    }


    Logger log = Logger.getLogger("ScanAllClass.class");

    //先获取本文件绝对路径
    //从本文件绝对路径下递归寻找所有类
    //遇到包则递归寻找
    //找到类则加入list
    /**
     * 扫描到的所有的类
     */
    private List<Class<?>> classes = new ArrayList<>();
    /**
     * 遇到Service则创建对应对象，准备自动装配
     */
    private Map<String, Object> objectMap = new HashMap<>();
    /**
     * 所扫描的基础包
     */
    private String basePackage;
    /**
     * 基础绝对路径长度
     */
    private int absolutePathLength;

    public <T> void start(Class<T> applicationClass) throws BeanBuilderException {
        basePackage = applicationClass.getPackage().getName();
        String absolutePath = applicationClass.getResource("").getPath();
        log.info("包位置:" + absolutePath);
        File file = new File(absolutePath);
        absolutePathLength = absolutePath.length();
        scanFolderInClass(file);
        SeekBeanUtil seekBeanUtil = new SeekBeanUtil(classes);

    }


    /**
     * 获取指定包下所有字节码的全类名
     *
     * @return
     */
    private List<String> getFullyQualifiedClassNameList() {
        return null;
    }

    /**
     * 扫描类后添加进list
     *
     * @param file 文件夹
     */
    private void scanFolderInClass(File file) {
        String[] fileNames = file.list();
        if (fileNames == null) {
            return;
        }
        //获取当前文件夹类包名
        String pack = new StringBuilder().append(file.getPath().substring(absolutePathLength - 2).replace("\\", "."))
                .append(".").toString();
        //筛选出所有class文件
        //获取所有文件名与类，存入map
        Arrays.stream(fileNames).filter(e -> e.endsWith(".class"))
                .forEach(e -> {
                    try {
                        Class<?> clazz = Class.forName(new StringBuilder().append(basePackage).append(pack)
                                                               .append(e, 0, e.lastIndexOf(".")).toString());
                        if (!clazz.isAnnotation()) {
                            classes.add(clazz);
                        }
                    } catch (ClassNotFoundException classNotFoundException) {
                        classNotFoundException.printStackTrace();
                    }

                });
        //筛选出所有非class文件
        //筛选出所有文件夹
        //进行递归获取文件名
        Arrays.stream(fileNames).filter(e -> !e.endsWith(".class")).map(e -> new File(file, e))
                .filter(File::isDirectory).forEach(this::scanFolderInClass);
    }


}
